/*
 * @Author: your name
 * @Date: 2021-12-06 15:35:12
 * @LastEditTime: 2021-12-24 17:28:54
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \express-app\controller.js
 */
const express = require('express');
const createError = require('http-errors');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const indexRouter = require('./routes/index');
const loginRouter = require('./routes/login');
const usersRouter = require('./routes/users');
const cors = require('cors');
const session = require('express-session');
const history = require('connect-history-api-fallback');
const MongoStore = require('connect-mongo');

module.exports = (app) => {
  // view engine setup
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'ejs');
  app.use(logger('dev'));
  // 获取post过来的数据
  app.use(express.json());
  app.use(express.urlencoded({ extended: false }));
  //配置cookie
  app.use(cookieParser());

  //这句代码需要在express.static上面
  app.use(
    history({
      htmlAcceptHeaders: [' text/html ', ' application/xhtml+xml '],
      verbose: true,
    })
  );
  //配置静态目录（根目录）
  app.use(express.static(path.join(__dirname, 'public')));
  //开启cors跨域
  app.use(cors());
  // session配置
  app.use(
    session({
      secret: 'this is session', //服务端生成session的签名（cookie中的key）
      resave: false, //强制保存session
      name: 'test', // cookie中的名称（cookie中的key ）
      cookie: {
        maxAge: 60 * 1000 * 60,
        secure: false, //true标识只有https才能访问cookie
      },
      httpOnly: false, //是否禁止客户端修改
      saveUninitialized: true, //强制未初始化的session存储
      rollback: false,
      store: MongoStore.create({
        mongoUrl: 'mongodb://localhost/test', //连接mongoDB的地址
        autoRemove: 'disabled',
        touchAfter: 60 * 60 * 4, // time period in seconds
      }),
    })
  );
  // session.destroy();清除session
  // 允许跨域
  // app.all('*', function(req, res, next) {
  //   // console.log(req.headers.origin)
  //   // console.log(req.environ)
  //   res.header("Access-Control-Allow-Origin", req.headers.origin); //cors核心代码
  //   // res.header("Access-Control-Allow-Origin", '*');

  // res.setHeader("Access-Control-Allow-Origin", '*');
  //   res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  //   res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  //   res.header("Access-Control-Allow-Credentials","true");
  //   res.header("X-Powered-By",' 3.2.1')
  //   if(req.method === "OPTIONS") res.send(200);/*让options请求快速返回*/
  //   else  next();
  // });

  // 统一中间件处理
  app.use(function (req, res, next) {
    console.log('处理token');
    next();
  });

  /**
   * 后端路由（由上往下匹配）
   */
  app.use('/', indexRouter);
  app.use('/login', loginRouter);
  app.use('/users', usersRouter);

  // catch 404 and forward to error handler
  app.use(function (req, res, next) {
    next(createError(404));
  });

  // error handler路由不存在的情况
  app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    // render the error page
    res.status(err.status || 500);
    res.render('error');
  });
};
